//
//  BDCityListHelper.m
//  BadBoy
//
//  Created by wen on 2017/4/19.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDCityListHelper.h"
#import "BDCityInfo.h"
#import "PinYin4Objc.h"

static NSString *startVersion = @"2";
static NSString *district_version = @"district_version";


@implementation BDCityListHelper

+ (void)judgeCityVersionWithVersion:(NSString *)version AgreeCity:(NSArray *)agreeCity{
    //保存允许城市
    [[NSUserDefaults standardUserDefaults] setObject:agreeCity forKey:agreeCityArrayStr];
    
    //第一次保存
    if (![[NSUserDefaults standardUserDefaults] objectForKey:district_version]) {
        [[NSUserDefaults standardUserDefaults] setObject:startVersion forKey:district_version];
    }
    
    if ([version isEqualToString:startVersion]) {
        //当数据是第一版的时候，读取本地数据保存
        [self getLocationCityList];
    }else{
        NSString *nowDistrict = [[NSUserDefaults standardUserDefaults] objectForKey:district_version];
        if (![nowDistrict isEqualToString:version]) {
            //开始网络请求新的数据
            [self getCityDataWithDistrict:version];
        }else{
            //根据当前开放城市重新变更列表
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                NSArray *cityList = [BDCityInfo getCityArray];
                [self creatCityListWithArray:cityList];
            });
        }
    }
}

//获取网络省市数据
+ (void)getCityDataWithDistrict:(NSString *)district{
    NSString *url = [NSString stringWithFormat:@"%@tool/district",KBDBaseURL];
    
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:nil automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [[NSUserDefaults standardUserDefaults] setObject:district forKey:district_version];
        NSArray *infoArray = [BDCityInfo mj_objectArrayWithKeyValuesArray:x];
        [self saveCityList:infoArray];
    }];
}

//获取本地数据，在网络数据加载失败的时候使用
+ (void)getLocationCityList{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cityList" ofType:@"plist"];
    NSArray *cityDicArr = [NSArray arrayWithContentsOfFile:path];
    NSArray *infoArray = [BDCityInfo mj_objectArrayWithKeyValuesArray:cityDicArr];
    [[NSUserDefaults standardUserDefaults] setObject:startVersion forKey:district_version];
    [self saveCityList:infoArray];
}

+ (void)saveCityList:(NSArray *)cityList{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self creatCityListWithArray:cityList];
        NSString *path = [DocumentPath stringByAppendingPathComponent:cityListPath];
        NSArray *saveArray = [BDCityInfo mj_keyValuesArrayWithObjectArray:cityList];
        if ([saveArray writeToFile:path atomically:YES]) {
//            // BDLog(ASLocalizedString(@"保存成功"));
        }
    });
}

+ (void)creatCityListWithArray:(NSArray *)firstCityArray{
//    // BDLog(ASLocalizedString(@"开始创建城市索引表"));
    NSArray *agreeCityArray = [[NSUserDefaults standardUserDefaults] objectForKey:agreeCityArrayStr];
    
    NSMutableArray *cityArr = [NSMutableArray array];
    for (BDCityInfo *cityInfo in firstCityArray) {
        if ([agreeCityArray containsObject:@(cityInfo.infoID)]) {
            if (cityInfo.type == BDCityTypeCity) {
                [cityArr addObject:cityInfo];
            }
        }
    }
    NSMutableArray *indexMutableArray = [NSMutableArray array];
    NSMutableDictionary *sectionMutableDictionary = [NSMutableDictionary dictionary];
    [self processDataWithCity:cityArr indexMutableArray:indexMutableArray sectionMutableDictionary:sectionMutableDictionary];
}

+ (void)processDataWithCity:(NSArray *)cityMutableArray indexMutableArray:(NSMutableArray *)indexMutableArray sectionMutableDictionary:(NSMutableDictionary *)sectionMutableDictionary{
    
    NSMutableArray *emptyArray = [NSMutableArray array];
    for (int i = 0; i < cityMutableArray.count; i ++) {
        BDCityInfo *cityInfo = cityMutableArray[i];
        if (![cityInfo.first_letter isNotEmpty]) {
            NSString *sourceText= cityInfo.name;
            HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
            [outputFormat setToneType:ToneTypeWithoutTone];
            [outputFormat setVCharType:VCharTypeWithV];
            [outputFormat setCaseType:CaseTypeLowercase];
//            NSTimeInterval startTime=[[NSDate date] timeIntervalSince1970];
            
//            // BDLog(ASLocalizedString(@"开始部分数据的补足"));
            [PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) {
                cityInfo.first_letter = [[pinYin substringToIndex:1] uppercaseString];
//                // BDLog(ASLocalizedString(@"完成部分数据的补足"));
                [emptyArray addObject:cityInfo];
            }];
        }else{
            //如果数组中没有这个索引，那么在数组中加入这个索引
            if (![indexMutableArray containsObject:cityInfo.first_letter]) {
                [indexMutableArray addObject:cityInfo.first_letter];
            }
            //根据索引取字典中的数组
            NSMutableArray *litArray = sectionMutableDictionary[cityInfo.first_letter];
            //如果字典为空，创建该字典
            if (litArray == nil) {
                litArray = [NSMutableArray array];
                [sectionMutableDictionary setObject:litArray forKey:cityInfo.first_letter];
            }
            //将名字加入字典
            [litArray addObject:cityInfo.name];
        }
    }
    
    if (emptyArray.count != 0) {
        [self processDataWithCity:emptyArray indexMutableArray:indexMutableArray sectionMutableDictionary:sectionMutableDictionary];
    }
    
    //将字母排序
    [indexMutableArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return obj1 > obj2;
    }];
    
    for (NSString *key in indexMutableArray) {
        NSMutableArray *litArr = sectionMutableDictionary[key];
        [litArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
    }
    
    //判断第一个是不是字母，如果不是放到最后一个
    BOOL isLetter = [self matchLetter:indexMutableArray[0]];
    if (!isLetter) {
        //获取数组的第一个元素
        NSString *firstStr = [indexMutableArray firstObject];
        //移除第一项元素
        [indexMutableArray removeObjectAtIndex:0];
        //插入到最后一个位置
        [indexMutableArray insertObject:firstStr atIndex:indexMutableArray.count];
    }
    
    //    [self.characterMutableArray addObjectsFromArray:_indexMutableArray];
//    NSData *cityData = [NSKeyedArchiver archivedDataWithRootObject:indexMutableArray];
//    NSData *sectionData = [NSKeyedArchiver archivedDataWithRootObject:sectionMutableDictionary];
    
    //拼音转换太耗时，这里把第一次转换结果存到单例中
    NSString *cityDataPath = [DocumentPath stringByAppendingPathComponent:@"cityData.plist"];
//    [[NSBundle mainBundle] pathForResource:@"cityData" ofType:@"plist"];
    if ([indexMutableArray writeToFile:cityDataPath atomically:YES]) {
        
    }
    NSString *sectionDataPath = [DocumentPath stringByAppendingPathComponent:@"sectionData.plist"];
//    [[NSBundle mainBundle] pathForResource:@"sectionData" ofType:@"plist"];
    if ([sectionMutableDictionary writeToFile:sectionDataPath atomically:YES]) {
//        // BDLog(ASLocalizedString(@"保存数据成功"));
    }
    
//    [[NSUserDefaults standardUserDefaults] setValue:cityData forKey:@"cityData"];
//    [[NSUserDefaults standardUserDefaults] setObject:sectionData forKey:@"sectionData"];
}

+ (BOOL)matchLetter:(NSString *)str {
    //判断是否以字母开头
    NSString *ZIMU = @"^[A-Za-z]+$";
    NSPredicate *regextestA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ZIMU];
    
    if ([regextestA evaluateWithObject:str] == YES)
        return YES;
    else
        return NO;
}
@end
